package com.chengxiaoxiao.web.controller;

import com.chengxiaoxiao.constant.Constants;
import com.chengxiaoxiao.utils.IDGenertor;
import com.chengxiaoxiao.utils.JSONUtils;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.FilenameUtils;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

//@WebServlet("/manager/upload")
public class UploadServlet extends HttpServlet {

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String op = request.getParameter("op");
        if ("appLogo".equalsIgnoreCase(op)) {
            setAppLogo(request, response);
        }
    }

    /**
     * 负责应用图标的上传
     *
     * @param request
     * @param response
     */
    private void setAppLogo(HttpServletRequest request, HttpServletResponse response) {

        HashMap<String, String> map = new HashMap<>();

        boolean isMultiPart = ServletFileUpload.isMultipartContent(request);
        if (!isMultiPart) {
            throw new RuntimeException("表单异常");
        }
        DiskFileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload sfu = new ServletFileUpload(factory);
        List<FileItem> list = new ArrayList<>();

        try {
            list = sfu.parseRequest(request);
        } catch (Exception e) {
            throw new RuntimeException("请求解析失败");
        }

        String path = "";

        for (FileItem item : list) {
            if (!item.isFormField()) {
                path = processupload(item);
            }
        }
        map.put(Constants.JSON_RESPONSE_KEY_STATUS, "ok");
        map.put(Constants.JSON_RESPONSE_KEY_ERRORMSG, "上传成功");
        map.put("src", path);

        JSONUtils.toJson(response, map);


    }

    /**
     * 处理上传文件逻辑
     *
     * @param item
     */
    private String processupload(FileItem item) {
        try {

            InputStream in = item.getInputStream();
            String fileName = item.getName();
            if (fileName != null) {
                fileName = FilenameUtils.getName(fileName);
            }
            /*+ "_" + fileName*/
            int index =fileName.indexOf(".");

            //创建唯一ID
            fileName = IDGenertor.genGUID()+fileName.substring(index,fileName.length());

            //创建目录
            String realPath = getServletContext().getRealPath("files");

            //创建子目录，按照日期存放
            String child = genChildDirectory(realPath);

            String filePath = realPath + File.separator + child;

            item.write(new File(filePath, fileName));


            String contextPath = getServletContext().getContextPath() + "/files";

            return contextPath + "/" + child + "/" + fileName;

        } catch (Exception e) {
            throw new RuntimeException("创建子文件夹失败");
        }

    }

    /**
     * 按照日期声称目录
     *
     * @param realPath
     * @return
     */
    private String genChildDirectory(String realPath) {

        Date date = new Date();
        DateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        String str = format.format(date);

        File file = new File(realPath, str);
        if (!file.exists()) {
            file.mkdirs();
        }
        return str;
    }
}
